﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Management;
using System.Diagnostics;

namespace Segmentator.Micro
{
    class CpUusage
    {
        private Thread thr1;
        private StreamWriter cpuwriter;
        private StreamWriter ramwriter;

        PerformanceCounter cpuCounter; // загрузка процессора
        PerformanceCounter ramCounter; // загрузка памяти
        private DateTime lastTime;
 
        public CpUusage()
        {
            cpuwriter = new StreamWriter("results.txt");
            ramwriter = new StreamWriter("ramresult");
            cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";
            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            lastTime = DateTime.Now;
        }

         public void start()
        {
            // Создание нового потока.
            thr1 = new Thread(new ThreadStart(toFileLoading));
            // Запуск нового потока.
            thr1.Start();
        }

        public void stop()
        {
            cpuwriter.WriteLine("Время выполнения = " + ((DateTime.Now - lastTime).Minutes*60 +((DateTime.Now - lastTime).Seconds)));
            cpuwriter.Close();
            ramwriter.Close();
            thr1.Abort();
        }

        void toFileLoading()
        {
            float value = 0, ram = 0;
            cpuwriter.WriteLine("Загруженность процессора в процентах");
            while(1==1)
            {
                value = cpuCounter.NextValue();
                ram = ramCounter.NextValue();
                cpuwriter.WriteLine(value+ "%");
                ramwriter.WriteLine(ram);
                Thread.Sleep(2000);
            }
           
          
        }

   

    }
}
